var lineReader = require('line-reader'),
    Promise = require('bluebird'),
    pinyin = require("pinyin"),
    fs = require("fs");

fs.appendFile('README.md',"## 这里是给小天真准备的作业解析\n> 点击左下方菜单按钮可以展开/折叠列表\n\n", function(err){
  if(err) throw err;
});

var eachLine = Promise.promisify(lineReader.eachLine);
eachLine('_sidebar_tmp.md', function(line) {
  const chnTitle = line.substring(line.indexOf('(')+1, line.indexOf(')'));
  const pinyin2Array = pinyin(chnTitle, {
    style: pinyin.STYLE_NORMAL,
    heteronym: true,
  });

  function reduceDimension(arr) {
      var reduced = [];
      for (var i = 0; i < arr.length; i++) {
          for (var j = 0; j < arr[i].length; j++) {
              if (/[a-zA-Z0-9]/.test(arr[i][j]) === true) {
                reduced.push(arr[i][j]);
              }
          }
      }
      return reduced;
  }
  const engTitle = reduceDimension(pinyin2Array).join('-').replace(/\s+/g,"");
  const title = ' - ' + '[' + chnTitle + ']' + '(' + engTitle + ')' + '\n';
  console.log(title);

  fs.rename(chnTitle + '.md', engTitle + '.md', function(err){
    if (err) {
      throw err;
    }
    console.log('rename done');
  })

  fs.appendFile('_sidebar.md',title,function(err){
    if(err) throw err;
    console.log('has finished');
  });

  fs.appendFile('README.md',title,function(err) {
    if(err) throw err;
  });

}).then(function(title) {
  return title;
}).catch(function(err) {
  console.error(err);
});
